<?php
namespace app\home\controller;

use think\Request;
use think\Db;
use app\common\logic\Upload;
use app\common\logic\Seller as Lseller;

/**
 * Seller Controller
 */
class Seller extends Common
{
    private $sellerObj;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->sellerObj = new Lseller();
    }

	/**
	 * 商铺列表
	 */
	public function index()
    {
        $userInfo = $this->getLoginUserInfo();
        $name = Request::instance()->get('name', '');
        $role = session('role');
        if ($role == 1) {//代理商
            $where = ['agency' => session('id')];
            $salesman = Request::instance()->get('salesman', '');
            if ($salesman) {
                $where['salesman'] = $salesman;
            }
            $agents = Db::name('agent')->where([
                'belong_agent' => $userInfo['session_id'],
                'is_use' => 1
            ])->order('id', 'desc')
                ->select();
            $this->assign('agents', $agents);
        } elseif ($role == 2) {//地推
            $where = ['salesman' => session('id')];
        } else {
            die('没有该权限');
        }

        if ($name) {
            $where['name'] = ['like', '%' . $name . '%'];
        }

        $sellers = Db::name('seller')
            ->where($where)
            ->order('id', 'desc')
            ->select();
        foreach ($sellers as &$item) {
            $item = $this->formatInfo($item);
        }
        return $this->fetch('index', [
            'sellers' => $sellers,
        ]);
    }

    /**
     * 获取详情
     */
    public function detail()
    {
        $userInfo = $this->getLoginUserInfo();

        $id = Request::instance()->get('id');

        $seller = Db::name('seller')->where([
            'id' => $id
        ])->find();

        if (!$seller) {
            $this->redirect(\think\Request::instance()->root().'/home/Seller/index');
        }

        return $this->fetch('detail', [
            'seller' => $seller,
        ]);
    }

    /**
     * 添加seller页面
     */
    public function add()
    {
        $userInfo = $this->getLoginUserInfo();

        // 地推
        $agents = Db::name('agent')
            ->field('id,real_name')
            ->where([
            'belong_agent' => $userInfo['session_id'],
            'is_use' => 1
            ])->order('id', 'desc')
            ->select();
        // 省份
        $provinceTmp = Db::name('address')->where("addr_pid=0")->field('addr_id,addr_name')->select();
        $province = [];
        foreach($provinceTmp as $val){
            $province[$val['addr_id']] = $val;
            $pids[] = $val['addr_id'];
        }

        // 城市
        $cityTmp = Db::name('address')->where("addr_pid in (".implode(",",$pids).")")->field('addr_id,addr_name,addr_pid')->select();
        $city = [];
        foreach($cityTmp as $val){
            $city[$val['addr_pid']][] = $val;
        }
        $this->assign('sale', $agents);
        $this->assign('province', $province);
        $this->assign('city', $city);
        return $this->fetch('add');
    }

    /**
     * 添加商铺
     */
    public function addSeller()
    {
        $userInfo = $this->getLoginUserInfo();

        $data = input();
        $data['agency'] = $userInfo['session_id'];
        $result = $this->sellerObj->addSeller($data);

        if ($result['code'] == 0) {
            $this->exit_msg_callback('backFunc', $result['msg'], 1);
        } else {
            $this->exit_msg_callback('backFunc', $result['msg']);
        }
    }


    /**
     * 修改seller页面
     */
    public function putPage()
    {
        $userInfo = $this->getLoginUserInfo();

        $id = Request::instance()->get('id');

        $seller = Db::name('seller')->where([
            'id' => $id,
            'agency' => $userInfo['session_id']
        ])->find();

        $seller = $this->formatInfo($seller);

        $agents = Db::name('agent')->where([
            'belong_agent' => $userInfo['session_id'],
            'is_use' => 1
        ])->order('id', 'desc')
            ->select();

        // 省份
        $provinceTmp = Db::name('address')->where("addr_pid=0")->field('addr_id,addr_name')->select();
        $province = [];
        foreach($provinceTmp as $val){
            $province[$val['addr_id']] = $val;
            $pids[] = $val['addr_id'];
        }

        // 城市
        $cityTmp = Db::name('address')->where("addr_pid in (".implode(",",$pids).")")->field('addr_id,addr_name,addr_pid')->select();
        $city = [];
        foreach($cityTmp as $val){
            $city[$val['addr_pid']][] = $val;
        }

        return $this->fetch('put', [
            'seller' => $seller,
            'agents' => $agents,
            'province' => $province,
            'city' => $city,
        ]);
    }

    /**
     * 修改商铺
     */
    public function putSeller()
    {
        $userInfo = $this->getLoginUserInfo();

        $data = input();
        $data['agency'] = $userInfo['session_id'];
        $result = $this->sellerObj->editSeller($data);

        if ($result['code'] == 0) {
            $this->exit_msg_callback('backFunc', $result['msg'],1);
        } else {
            $this->exit_msg_callback('backFunc', $result['msg']);
        }
    }

    /**
     * 格式化信息
     */
    public function formatInfo($item)
    {
        $agent = Db::name('agent')
            ->where([
                'id' => $item['salesman']
            ])
            ->find();
        $item['real_name'] = '';
        if ($agent) {
            $item['real_name'] = $agent['real_name'];
        }

        $item['shopstart'] = $this->sellerObj->parseTime($item['shopstart']);
        $item['shopend'] = $this->sellerObj->parseTime($item['shopend']);

        $item['all_image'] = [];
        if(!empty($item['picture'])){
            $card_pic = '';
            $init_image = trim($item['picture'], ',');
            $img_list = explode(',', $init_image);
            $item['all_image'] = [];
            $url = config('txyunview');
            foreach ($img_list as $img) {
                $name = explode('/', $img);
                $name = array_pop($name);
                $item['all_image'][] = ['name' => $name, 'url' => $url.$img];
                $card_pic .= $url.$img.',';
            }
            $item['picture'] = trim($card_pic, ',');
        }

        $item['all_image'] = json_encode($item['all_image'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

        return $item;
    }

    /**
     * 上传图片
     */
    public function fileUpload()
    {
        $fileObj = new Upload();
        $dstPath = 'operator/Seller/';
        $res = $fileObj->upload('img_file', $dstPath, 1024*1024*10);
        if ($res['code'] == 0) {
            return json($res['msg']);
        } else {
            return json($res['msg']);
        }
    }
}

